package org.example.server.server.handler;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.example.server.server.NettyChannelManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @title
 * @time 2025/6/16 16:17
 */
@Component
@ChannelHandler.Sharable
@Slf4j
public class NettyServerHandler  extends ChannelInboundHandlerAdapter {
    @Autowired
    private NettyChannelManager channelManager;


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        channelManager.add(ctx.channel());
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        channelManager.remove(ctx.channel());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("[exceptionCaught][连接:{}],发生异常:",ctx.channel().id(), cause);
        // 断开连接
        ctx.channel().close();
    }
}
